package com.xinghai.system.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xinghai.common.annotation.DataScope;
import com.xinghai.common.utils.DateUtils;
import com.xinghai.common.utils.StringUtils;
import com.xinghai.system.domain.*;
import com.xinghai.system.domain.dto.*;
import com.xinghai.system.domain.vo.XhStaticsReportQueryVo;
import com.xinghai.system.domain.vo.XhVehicleInfoQueryVo;
import com.xinghai.system.mapper.DingUserMapper;
import com.xinghai.system.mapper.SysDeptMapper;
import com.xinghai.system.mapper.XhUseVehicleInfoMapper;
import com.xinghai.system.mapper.XhVehicleOrderInfoMapper;
import com.xinghai.system.service.*;
import com.xinghai.system.util.XHConstant;
import com.xinghai.system.util.XHUtils;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import static com.xinghai.common.utils.SecurityUtils.getDeptId;
import static com.xinghai.common.utils.SecurityUtils.getUsername;

/**
 * 用车订单Service业务层处理
 * 
 * @author xinghai
 * @date 2024-07-23
 */
@Service
public class XhVehicleOrderInfoServiceImpl extends ServiceImpl<XhVehicleOrderInfoMapper, XhVehicleOrderInfo> implements IXhVehicleOrderInfoService
{
    @Autowired
    private XhVehicleOrderInfoMapper xhVehicleOrderInfoMapper;

    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    @Autowired
    private IXhDriverInfoService xhDriverInfoService;

    @Autowired
    private IXhVehicleOrderHisService xhVehicleOrderHisService;

    @Autowired
    private IXhVehicleOrderCarHisService xhVehicleOrderCarHisService;

    @Autowired
    private IXhCarInfoService xhCarInfoService;

    @Autowired
    private XhUseVehicleInfoMapper xhUseVehicleInfoMapper;

    @Autowired
    private IXhUseVehicleInfoService xhUseVehicleInfoService;
    @Autowired
    private DingdingOaService dingdingOaService;

    @Autowired
    private DingUserMapper dingUserMapper;
    @Autowired
    private SysDeptMapper sysDeptMapper;

    /**
     * 查询用车订单
     * 
     * @param id 用车订单主键
     * @return 用车订单
     */
    @Override
    public XhVehicleOrderInfo getInfo(Long id)
    {
        return xhVehicleOrderInfoMapper.getInfo(id);
    }

    /**
     * 查询用车订单列表
     * 
     * @param xhVehicleOrderInfo 用车订单
     * @return 用车订单
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<XhVehicleOrderInfoDTO> list(XhVehicleOrderInfo xhVehicleOrderInfo)
    {
        xhVehicleOrderInfo.setDelFlag("0");
        List<XhVehicleOrderInfoDTO> list = xhVehicleOrderInfoMapper.list(xhVehicleOrderInfo);
        //查询临时司机信息
        list.forEach(item->{
            //从用车历史中查询临时司机信息
            XhVehicleOrderCarHis orderCarHis = xhVehicleOrderCarHisService.lambdaQuery()
                    .eq(XhVehicleOrderCarHis::getVehicleId,item.getVehicleId())
                    .orderByDesc(XhVehicleOrderCarHis::getCreateTime)
                    .last(" limit 1").one();
            if (orderCarHis != null && StringUtils.isNotNull(orderCarHis.getAppendDriverInfo())){
                String appendDriverName = String.join(",",JSON.parseArray(orderCarHis.getAppendDriverInfo(),XhDriverInfo.class).stream().map(XhDriverInfo::getDriverName).collect(Collectors.toList()));
                item.setDriverName(StringUtils.isNotEmpty(item.getDriverName())?(item.getDriverName() + "," + appendDriverName):appendDriverName);
            }
            //始发地格式转换
            if (StringUtils.isNotNull(item.getBeginAddr())){
                item.setBeginAddr(XHUtils.parseBeginAddr(item.getBeginAddr()));
            }
        });
        return list;
    }

    /**
     * 新增用车订单
     * 
     * @param xhVehicleOrderInfo 用车订单
     * @return 结果
     */
    @Override
    public int insert(XhVehicleOrderInfo xhVehicleOrderInfo)
    {
        xhVehicleOrderInfo.setCreateTime(DateUtils.getNowDate());
        return xhVehicleOrderInfoMapper.insert(xhVehicleOrderInfo);
    }
    /**
     * 批量新增用车订单
     *
     * @param xhVehicleOrderInfoList 用车订单
     * @return 结果
     */
    @Override
    public int insertBatch(List<XhVehicleOrderInfo> xhVehicleOrderInfoList)
    {
        return xhVehicleOrderInfoMapper.insertBatch(xhVehicleOrderInfoList);
    }
    /**
     * 修改用车订单
     * 
     * @param xhVehicleOrderInfo 用车订单
     * @return 结果
     */
    @Override
    public int update(XhVehicleOrderInfo xhVehicleOrderInfo)
    {
        xhVehicleOrderInfo.setUpdateTime(DateUtils.getNowDate());
        return xhVehicleOrderInfoMapper.update(xhVehicleOrderInfo);
    }

    /**
     * 批量删除用车订单
     * 
     * @param ids 需要删除的用车订单主键
     * @return 结果
     */
    @Override
    public int deleteBatch(Long[] ids)
    {
        return xhVehicleOrderInfoMapper.deleteBatch(ids);
    }

    /**
     * 删除用车订单信息
     * 
     * @param id 用车订单主键
     * @return 结果
     */
    @Override
    public int delete(Long id)
    {
        return xhVehicleOrderInfoMapper.delete(id);
    }

    /**
     * 导入用车订单信息
     *
     * @param list 用车订单信息集合
     * @return 结果
     */
    @Override
    @Transactional
    public boolean importData(List<XhVehicleOrderInfo> list){
        SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
        try {
            XhVehicleOrderInfoMapper xhVehicleOrderInfoMapper = sqlSession.getMapper(XhVehicleOrderInfoMapper.class);
            list.stream().forEach(item -> xhVehicleOrderInfoMapper.insert(item));
            // 提交数据
            sqlSession.commit();
            sqlSession.rollback();
        } catch (Exception e) {
            sqlSession.rollback();
            return false;
        } finally {
            sqlSession.close();
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int acceptOrder(XhVehicleOrderInfo xhVehicleOrderInfo) throws Exception {
        //查询当前任务
        this.checkParam(xhVehicleOrderInfo);
        //查询任务
        XhVehicleOrderInfo orderDB = this.getById(xhVehicleOrderInfo.getId());
        //校验状态,非待接单状态 进行提醒
        if (!XHConstant.ORDER_STATUS_WAIT.equals(orderDB.getStatus())){
            throw new Exception("当前订单状态非待接单，不允许重复接单");
        }
        //定义拼接对象
        StringBuilder stringBuilder = new StringBuilder();
        //查询司机信息
        if (!xhVehicleOrderInfo.getDriverIdList().isEmpty()){
            List<XhDriverInfo> xhDriverInfoList = xhDriverInfoService.lambdaQuery().in(XhDriverInfo::getId,xhVehicleOrderInfo.getDriverIdList()).list();
            xhDriverInfoList.forEach(item->{
                stringBuilder.append("司机姓名："+item.getDriverName()+"("+item.getDriverPhone()+"); ");
            });
        }

        //填充车辆记录
        XhVehicleOrderCarHis orderCarHis = new XhVehicleOrderCarHis();
        //新增司机信息
        if (!xhVehicleOrderInfo.getAppendDriverList().isEmpty()){
            xhVehicleOrderInfo.getAppendDriverList().forEach(item->{
                stringBuilder.append("司机姓名："+item.getDriverName()+"("+item.getDriverPhone()+"); ");
            });
            //存储后回显使用
            orderCarHis.setAppendDriverInfo(JSONObject.toJSONString(xhVehicleOrderInfo.getAppendDriverList()));
        }
        orderCarHis.setVehicleId(orderDB.getVehicleId());
        orderCarHis.setCarId(xhVehicleOrderInfo.getCarId());
        orderCarHis.setDriverInfo(stringBuilder.toString());
        orderCarHis.setRemark("车辆分配");
        orderCarHis.setCreateBy(getUsername());
        orderCarHis.setCreateTime(DateUtils.getNowDate());
        xhVehicleOrderCarHisService.save(orderCarHis);

        //填充接单记录
        XhVehicleOrderHis xhVehicleOrderHis = new XhVehicleOrderHis();
        xhVehicleOrderHis.setVehicleId(orderDB.getVehicleId());
        xhVehicleOrderHis.setDeptId(orderDB.getDeptId());
        xhVehicleOrderHis.setCreateTime(DateUtils.getNowDate());
        xhVehicleOrderHis.setCreateBy(getUsername());
        xhVehicleOrderHis.setRemark("接收订单");
        orderCarHis.setCreateBy(getUsername());
        orderCarHis.setCreateTime(DateUtils.getNowDate());
        xhVehicleOrderHisService.save(xhVehicleOrderHis);

        //更新接单状态
        orderDB.setStatus(XHConstant.ORDER_STATUS_PROCESS);
        orderDB.setAcceptBy(getUsername());
        orderDB.setAcceptTime(DateUtils.getNowDate());
        orderDB.setUpdateTime(DateUtils.getNowDate());
        orderDB.setDriverId(String.join(",", xhVehicleOrderInfo.getDriverIdList()));
        orderDB.setCarId(xhVehicleOrderInfo.getCarId());
        int update = xhVehicleOrderInfoMapper.update(orderDB);
        //生成合同
        dingdingOaService.downloadContract(orderDB.getId());
        return update;
    }

    private void checkParam(XhVehicleOrderInfo xhVehicleOrderInfo ) throws Exception {
        if (xhVehicleOrderInfo.getId() == null){
            throw new Exception("请选择待接收订单");
        }
        if (xhVehicleOrderInfo.getCarId() == null){
            throw new Exception("请为接收订单设置车辆信息");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int refuseOrder(XhVehicleOrderInfo xhVehicleOrderInfo) throws Exception {
        //查询任务
        XhVehicleOrderInfo orderDB = this.getById(xhVehicleOrderInfo.getId());
        if (orderDB == null){
            throw new Exception("当前订单不存在");
        }
        //校验状态,非待接单状态 进行提醒
        if (!XHConstant.ORDER_STATUS_WAIT.equals(orderDB.getStatus())){
            throw new Exception("当前订单状态非待接单，不允许拒绝接单");
        }

        //填充拒绝接单记录
        XhVehicleOrderHis xhVehicleOrderHis = new XhVehicleOrderHis();
        xhVehicleOrderHis.setVehicleId(orderDB.getVehicleId());
        xhVehicleOrderHis.setDeptId(getDeptId());
        xhVehicleOrderHis.setCreateTime(DateUtils.getNowDate());
        xhVehicleOrderHis.setCreateBy(getUsername());
        xhVehicleOrderHis.setRemark("拒绝订单");
        xhVehicleOrderHisService.save(xhVehicleOrderHis);

        //拒绝
        orderDB.setStatus(XHConstant.ORDER_STATUS_REFUSE);
        if (xhVehicleOrderInfoMapper.updateById(orderDB) == 1){
            //发送钉钉消息 TODO smy 拒绝需要给专车人员发送钉钉消息
        }
        return 1;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int changeOrder(XhVehicleOrderInfo xhVehicleOrderInfo) throws Exception {
        //查询当前任务
        this.checkParam(xhVehicleOrderInfo);
        //查询任务
        XhVehicleOrderInfo orderDB = this.getById(xhVehicleOrderInfo.getId());
        //校验状态,审批中、进行中允许变更 结合 流程节点一起判断修改条件 TODO smy 确定好流程节点后，追加判断条件
        if (!XHConstant.ORDER_STATUS_APPLY.equals(orderDB.getStatus())
                && !XHConstant.ORDER_STATUS_PROCESS.equals(orderDB.getStatus())){
            throw new Exception("当前订单状态非待接单，不允许重复接单");
        }

        //定义拼接对象
        StringBuilder stringBuilder = new StringBuilder();
        //查询司机信息
        if (!xhVehicleOrderInfo.getDriverIdList().isEmpty()){
            List<XhDriverInfo> xhDriverInfoList = xhDriverInfoService.lambdaQuery().in(XhDriverInfo::getId,xhVehicleOrderInfo.getDriverIdList()).list();
            xhDriverInfoList.forEach(item->{
                stringBuilder.append("司机姓名："+item.getDriverName()+"("+item.getDriverPhone()+"); ");
            });
        }

        //填充车辆记录
        XhVehicleOrderCarHis orderCarHis = new XhVehicleOrderCarHis();
        //新增司机信息
        if (!xhVehicleOrderInfo.getAppendDriverList().isEmpty()){
            xhVehicleOrderInfo.getAppendDriverList().forEach(item->{
                stringBuilder.append("司机姓名："+item.getDriverName()+"("+item.getDriverPhone()+"); ");
            });
            //存储后回显使用
            orderCarHis.setAppendDriverInfo(JSONObject.toJSONString(xhVehicleOrderInfo.getAppendDriverList()));
        }
        orderCarHis.setVehicleId(orderDB.getVehicleId());
        orderCarHis.setCarId(xhVehicleOrderInfo.getCarId());
        orderCarHis.setDriverInfo(stringBuilder.toString());
        orderCarHis.setRemark("车辆变更");
        orderCarHis.setCreateBy(getUsername());
        orderCarHis.setCreateTime(DateUtils.getNowDate());
        xhVehicleOrderCarHisService.save(orderCarHis);
        //更新司机信息
        orderDB.setDriverId(String.join(",",xhVehicleOrderInfo.getDriverIdList()));
        orderDB.setCarId(xhVehicleOrderInfo.getCarId());
        return xhVehicleOrderInfoMapper.updateById(orderDB);
    }

    @Override
    public XhVehicleWaitChangeDTO waitChangeInfo(XhVehicleOrderInfo xhVehicleOrderInfo) throws Exception {
        //查询主表信息
        if (xhVehicleOrderInfo.getId() == null){
            throw new Exception("请选择需要变更订单");
        }
        XhVehicleOrderInfo xhVehicleOrderInfoDB = this.getById(xhVehicleOrderInfo.getId());
        if (xhVehicleOrderInfoDB == null){
            throw new Exception("选择的变更订单不存在");
        }

        //返回结果
        XhVehicleWaitChangeDTO waitChangeDTO = new XhVehicleWaitChangeDTO();
        //查询车辆信息
        XhCarInfo xhCarInfo = xhCarInfoService.getById(xhVehicleOrderInfoDB.getCarId());
        if (xhCarInfo != null){
            waitChangeDTO.setCarType(xhCarInfo.getCarType());
            //校验司机信息
            if (StringUtils.isNotNull(xhCarInfo.getDriverId())){
                //查询司机信息
                List<XhDriverInfo> driverInfoList = xhDriverInfoService.lambdaQuery().in(XhDriverInfo::getId, Arrays.asList(xhVehicleOrderInfoDB.getDriverId().split(",")))
                        .orderByDesc(XhDriverInfo::getCreateTime).list();
                waitChangeDTO.setDriverIdList(driverInfoList);
            }
        }
        //查询临时新增司机信息
        Optional.ofNullable(xhVehicleOrderCarHisService.lambdaQuery()
                .eq(XhVehicleOrderCarHis::getVehicleId,xhVehicleOrderInfoDB.getVehicleId())
                .orderByDesc(XhVehicleOrderCarHis::getCreateTime)
                .last(" limit 1").one()).ifPresent(val->{
                    if (StringUtils.isNotNull(val.getAppendDriverInfo())){
                        waitChangeDTO.setAppendDriverList(JSON.parseArray(val.getAppendDriverInfo(), XhDriverInfo.class));
                    }
        });
        //物流公司
        Optional.ofNullable(sysDeptMapper.selectDeptById(xhVehicleOrderInfoDB.getDeptId())).ifPresent(val->{
            waitChangeDTO.setDeptName(val.getDeptName());
        });
        waitChangeDTO.setId(xhVehicleOrderInfoDB.getId());
        waitChangeDTO.setVehicleId(xhVehicleOrderInfo.getVehicleId());
        waitChangeDTO.setCarId(xhVehicleOrderInfoDB.getCarId());
        return waitChangeDTO;
    }

    @Override
    public List<XhVehicleOrderInfo> selectBatchByVehicleIds(List<Long> vehicleIds) {
        return xhVehicleOrderInfoMapper.selectBatchByVehicleIds(vehicleIds);
    }

    @Override
    public List<XhUseVehicleInfoDto> getListByStatus(XhVehicleInfoQueryVo xhVehicleInfoQueryVo, String status) {
        List<XhUseVehicleInfoDto> list = xhUseVehicleInfoService.getListByStatus(xhVehicleInfoQueryVo,status);
        list.stream().forEach(item -> {
            //[{北京市,北京市,东城区=1111}, {河北省,唐山市,路北区=111}]
            if (StringUtils.isNotEmpty(item.getBeginAddr())) {
                String beginAddr = xhUseVehicleInfoService.parseBeginAddr(item.getBeginAddr());
                item.setBeginAddr(beginAddr);
            }
        });
        return list;
    }

    @Override
    public void updateStatusByProcessInstanceId(String processInstanceId, String status) {
        xhVehicleOrderInfoMapper.updateStatusByProcessInstanceId(processInstanceId,status);
    }

    @Override
    public XhVehicleOrderInfo selectVehicleOrderInfoByVehicleId(Long vehicleId) {
        LambdaQueryWrapper<XhVehicleOrderInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(XhVehicleOrderInfo::getVehicleId,vehicleId);
        return xhVehicleOrderInfoMapper.selectOne(queryWrapper);
    }

    @Override
    public List<ProjectFeeDetailDTO> projectFeeDetailPage(XhStaticsReportQueryVo xhStaticsReportQueryVo) {
        if (StringUtils.isNull(xhStaticsReportQueryVo.getDateFlag())){
            //默认查询0
            xhStaticsReportQueryVo.setDateFlag(XHConstant.STR_0);
        }
        return xhVehicleOrderInfoMapper.projectFeeDetailPage(xhStaticsReportQueryVo);
    }

    @Override
    public List<DeptFeeDetailDTO> deptFeeDetailPage(XhStaticsReportQueryVo xhStaticsReportQueryVo) {
        return xhVehicleOrderInfoMapper.deptFeeDetailPage(xhStaticsReportQueryVo);
    }

    @Override
    public List<XhVehicleOrderInfoDTO> expiresList(XhVehicleOrderInfo xhVehicleOrderInfo) {

        List<XhVehicleOrderInfoDTO> xhVehicleOrderInfoDTOS = xhVehicleOrderInfoMapper.expiresList(xhVehicleOrderInfo);
        xhVehicleOrderInfoDTOS.forEach(item->{
            if (StringUtils.isNotEmpty(item.getBeginAddr())) {
                item.setBeginAddr(XHUtils.parseBeginAddr(item.getBeginAddr()));
            }
        });
        return xhVehicleOrderInfoDTOS;
    }

    @Override
    public List<TransferDetailDTO> transferDetailPage(XhStaticsReportQueryVo xhStaticsReportQueryVo) {
        List<TransferDetailDTO> detailDTOList = xhVehicleOrderInfoMapper.transferDetailPage(xhStaticsReportQueryVo);
        detailDTOList.forEach(item->{
            if (StringUtils.isNotEmpty(item.getBeginAddr())) {
                item.setBeginAddr(XHUtils.parseBeginAddr(item.getBeginAddr()));
            }
        });
        return detailDTOList;
    }
}
